package com.stone.zk.lock.config;

import com.stone.zk.lock.config.properties.ZkLockConfigProperties;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * zk分布式锁自动配置
 *
 * @author Mr_wenpan@163.com 2021/08/02 11:55
 */
@Configuration
@EnableConfigurationProperties(ZkLockConfigProperties.class)
public class ZkLockAutoConfiguration {

    /**
     * 注入CuratorFramework对象，用来创建分布式锁，其中start是初始化方法，close是注销方法
     *
     * @return CuratorFramework
     */
    @Bean(initMethod = "start", destroyMethod = "close")
    public CuratorFramework getCuratorFramework(ZkLockConfigProperties zkLockConfigProperties) {
        // 设置重试规则
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zkLockConfigProperties.getBaseSleepTimeMs(),
                zkLockConfigProperties.getMaxRetries());
        // Zookeeper客户端
        return CuratorFrameworkFactory.builder()
                .connectString(zkLockConfigProperties.getConnectString())
                .sessionTimeoutMs(zkLockConfigProperties.getSessionTimeoutMs())
                .connectionTimeoutMs(zkLockConfigProperties.getConnectionTimeoutMs())
                .retryPolicy(retryPolicy)
                .build();
    }
}
